<template>
  <div class="quote-container">
    <a-card :bordered="false">
      <!-- 搜索表单 -->
      <a-form layout="inline" :model="queryParams" @finish="handleQuery" class="search-form">
        <a-form-item label="报价单号" name="quoteNo">
          <a-input v-model:value="queryParams.quoteNo" placeholder="请输入报价单号"/>
        </a-form-item>
        <a-form-item label="客户名称" name="customerName">
          <a-input v-model:value="queryParams.customerName" placeholder="请输入客户名称"/>
        </a-form-item>
        <a-form-item label="销售人员" name="salesPerson">
          <a-input v-model:value="queryParams.salesPerson" placeholder="请输入销售人员"/>
        </a-form-item>
        <a-form-item label="状态" name="status">
          <a-select v-model:value="queryParams.status" placeholder="请选择状态" style="width: 120px" allow-clear>
            <a-select-option v-for="item in quoteStatusOptions" :key="item.value" :value="item.value">
              {{ item.label }}
            </a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item>
          <a-space>
            <a-button type="primary" html-type="submit">
              <template #icon>
                <search-outlined/>
              </template>
              查询
            </a-button>
            <a-button @click="resetQuery">
              <template #icon>
                <redo-outlined/>
              </template>
              重置
            </a-button>
          </a-space>
        </a-form-item>
      </a-form>

      <!-- 操作按钮 -->
      <div class="table-operations">
        <a-space>
          <a-button type="primary" @click="handleAdd">
            <template #icon>
              <plus-outlined/>
            </template>
            新增
          </a-button>
          <a-button type="primary" danger :disabled="!selectedRowKeys.length" @click="handleBatchDelete">
            <template #icon>
              <delete-outlined/>
            </template>
            批量删除
          </a-button>
          <a-button @click="handleExport">
            <template #icon>
              <file-excel-outlined/>
            </template>
            导出
          </a-button>
          <a-tag v-if="queryParams.customerId" color="blue" closable @close="clearCustomerFilter">
            客户筛选: {{ queryParams.customerName }}
          </a-tag>
        </a-space>
      </div>

      <!-- 数据表格 -->
      <a-table
          :columns="columns"
          :data-source="quoteList"
          :loading="loading"
          :pagination="pagination"
          :row-selection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange }"
          :row-key="(record: Quote) => record.quoteId"
          @change="handleTableChange"
      >
        <!-- 状态列 -->
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'status'">
            <a-tag :color="getStatusInfo(record.status).color">
              {{ getStatusInfo(record.status).label }}
            </a-tag>
          </template>

          <!-- 金额列 -->
          <template v-if="column.key === 'totalAmount'">
            ¥{{ formatCurrency(record.totalAmount) }}
          </template>
          <template v-if="column.key === 'discountAmount'">
            ¥{{ formatCurrency(record.discountAmount) }}
          </template>
          <template v-if="column.key === 'finalAmount'">
            ¥{{ formatCurrency(record.finalAmount) }}
          </template>

          <!-- 操作列 -->
          <template v-if="column.key === 'operation'">
            <a-space>
              <a @click="handleView(record)">查看</a>
              <a-divider type="vertical"/>
              <!-- 仅当状态为草稿(1)或已拒绝(4)时允许编辑 -->
              <a @click="handleEdit(record)" v-if="record.status === 1 || record.status === 4">编辑</a>
              <span v-else class="disabled-action">编辑</span>
              <a-divider type="vertical"/>
              <a-popconfirm
                  title="确定要删除这个报价单吗？"
                  ok-text="确定"
                  cancel-text="取消"
                  @confirm="handleDelete(record)"
              >
                <a class="danger-text">删除</a>
              </a-popconfirm>
              <!-- 仅当状态为草稿(1)或已拒绝(4)时允许提交 -->
              <template v-if="record.status === 1 || record.status === 4">
                <a-divider type="vertical"/>
                <a @click="handleSubmitQuote(record)">提交</a>
              </template>
              <template v-if="record.status === 2">
                <a-divider type="vertical"/>
                <a @click="handleReceiveQuote(record)">接收</a>
                <a-divider type="vertical"/>
                <a @click="handleRejectQuote(record)">拒绝</a>
              </template>
            </a-space>
          </template>
        </template>
      </a-table>
    </a-card>

    <!-- 报价单表单对话框 -->
    <quote-form
        v-model:visible="formVisible"
        :form-data="formData"
        @success="handleSuccess"
    />

    <!-- 报价单详情对话框 -->
    <quote-detail
        v-model:visible="detailVisible"
        :quote="detailData"
        @success="handleSuccess"
        @edit="handleEditFromDetail"
    />
  </div>
</template>

<script setup lang="ts">
import {onMounted, reactive, ref} from 'vue'
import {useRoute} from 'vue-router'
import type {TableProps} from 'ant-design-vue'
import {message} from 'ant-design-vue'
import {DeleteOutlined, FileExcelOutlined, PlusOutlined, RedoOutlined, SearchOutlined} from '@ant-design/icons-vue'
import {usePermission} from '@/composables/usePermission'
import type {Quote, QuoteSearch} from '@/types/quote'
import {getQuoteStatusInfo, quoteStatusOptions} from '@/types/quote'
import * as quoteApi from '@/api/quote'
import {formatCurrency} from '@/utils/format'

// 引入子组件
import QuoteForm from './components/QuoteForm.vue'
import QuoteDetail from './components/QuoteDetail.vue'

// 权限检查
const {checkPermission: hasPermission} = usePermission()

// 报价单状态
const loading = ref(false)
const quoteList = ref<Quote[]>([])
const pagination = reactive({
  current: 1,
  pageSize: 10,
  total: 0,
  showSizeChanger: true,
  showTotal: (total: number) => `共 ${total} 条记录`
})

// 查询参数
const queryParams = reactive<QuoteSearch>({
  quoteNo: '',
  customerName: '',
  salesPerson: '',
  status: undefined,
  customerId: undefined
})

// 选中行数据
const selectedRowKeys = ref<(string | number)[]>([])

// 表单状态
const formVisible = ref(false)
const formData = ref<Partial<Quote & { readOnly?: boolean }>>({})

// 详情状态
const detailVisible = ref(false)
const detailData = ref<Quote | undefined>()

// 表格列定义
const columns = [
  {
    title: '报价单ID',
    dataIndex: 'quoteId',
    key: 'quoteId',
    width: 80
  },
  {
    title: '报价单号',
    dataIndex: 'quoteNo',
    key: 'quoteNo'
  },
  {
    title: '客户名称',
    dataIndex: 'customerName',
    key: 'customerName'
  },
  {
    title: '总价',
    dataIndex: 'totalAmount',
    key: 'totalAmount'
  },
  {
    title: '优惠金额',
    dataIndex: 'discountAmount',
    key: 'discountAmount'
  },
  {
    title: '最终金额',
    dataIndex: 'finalAmount',
    key: 'finalAmount'
  },
  {
    title: '状态',
    dataIndex: 'status',
    key: 'status'
  },
  {
    title: '销售人员',
    dataIndex: 'salesPerson',
    key: 'salesPerson'
  },
  {
    title: '报价人电话',
    dataIndex: 'salerPhone',
    key: 'salerPhone'
  },
  {
    title: '有效期(天)',
    dataIndex: 'validDays',
    key: 'validDays'
  },
  {
    title: '创建时间',
    dataIndex: 'createTime',
    key: 'createTime',
    sorter: true
  },
  {
    title: '操作',
    key: 'operation',
    width: 250
  }
]

// 获取状态信息
const getStatusInfo = (status: number) => {
  return getQuoteStatusInfo(status)
}

// 初始化加载数据
onMounted(() => {
  // 检查是否有URL参数
  const route = useRoute()
  if (route.query.customerId) {
    queryParams.customerId = Number(route.query.customerId)
    queryParams.customerName = route.query.customerName as string || ''
  }

  getList()
})

// 获取报价单列表
const getList = async () => {
  loading.value = true
  try {
    const params = {
      ...queryParams,
      pageNum: pagination.current,
      pageSize: pagination.pageSize
    }

    const res = await quoteApi.getQuotePage(params)
    quoteList.value = res.rows || []
    pagination.total = res.total || 0
  } finally {
    loading.value = false
  }
}

// 查询
const handleQuery = () => {
  pagination.current = 1
  getList()
}

// 重置查询
const resetQuery = () => {
  Object.keys(queryParams).forEach(key => {
    // @ts-ignore
    queryParams[key] = key === 'status' ? undefined : ''
  })
  pagination.current = 1
  getList()
}

// 表格变化处理
const handleTableChange: TableProps['onChange'] = (pag, filters, sorter) => {
  pagination.current = pag.current as number
  pagination.pageSize = pag.pageSize as number
  getList()
}

// 选择行变化
const onSelectChange = (keys: (string | number)[]) => {
  selectedRowKeys.value = keys
}

// 新增报价单
const handleAdd = () => {
  formData.value = {}
  formVisible.value = true
}

// 查看报价单
const handleView = async (record: Quote) => {
  try {
    const quoteDetail = await quoteApi.getQuoteDetail(record.quoteId)
    detailData.value = quoteDetail
    detailVisible.value = true
  } catch (error) {
    message.error('获取报价单详情失败')
    console.error('获取报价单详情失败:', error)
  }
}

// 从详情页面编辑
const handleEditFromDetail = (quote: Quote) => {
  formData.value = {...quote, readOnly: false}
  formVisible.value = true
}

// 编辑报价单
const handleEdit = async (record: Quote) => {
  try {
    const quoteDetail = await quoteApi.getQuoteDetail(record.quoteId)
    formData.value = {...quoteDetail, readOnly: false}
    formVisible.value = true
  } catch (error) {
    message.error('获取报价单详情失败')
    console.error('获取报价单详情失败:', error)
  }
}

// 删除报价单
const handleDelete = async (record: Quote) => {
  try {
    await quoteApi.deleteQuote(record.quoteId)
    message.success('删除成功')
    if (pagination.current === 1) {
      getList()
    } else {
      pagination.current = 1
      getList()
    }
  } catch (error) {
    message.error('删除失败')
  }
}

// 批量删除
const handleBatchDelete = async () => {
  if (!selectedRowKeys.value.length) {
    message.warning('请至少选择一条记录')
    return
  }

  try {
    // 循环调用单个删除接口
    for (const quoteId of selectedRowKeys.value) {
      await quoteApi.deleteQuote(quoteId as number)
    }
    message.success('批量删除成功')
    pagination.current = 1
    getList()
    selectedRowKeys.value = []
  } catch (error) {
    message.error('批量删除失败')
  }
}

// 提交报价单
const handleSubmitQuote = async (record: Quote) => {
  try {
    await quoteApi.submitQuote(record.quoteId)
    message.success('提交成功')
    getList()
  } catch (error) {
    message.error('提交失败')
  }
}

// 接收报价单
const handleReceiveQuote = async (record: Quote) => {
  try {
    await quoteApi.receiveQuote(record.quoteId)
    message.success('接收成功')
    getList()
  } catch (error) {
    message.error('接收失败')
  }
}

// 拒绝报价单
const handleRejectQuote = async (record: Quote) => {
  try {
    await quoteApi.rejectQuote(record.quoteId)
    message.success('拒绝成功')
    getList()
  } catch (error) {
    message.error('拒绝失败')
  }
}

// 清除客户筛选条件
const clearCustomerFilter = () => {
  queryParams.customerId = undefined
  queryParams.customerName = ''
  getList()
}

// 导出报价单
const handleExport = () => {
  message.info('导出功能待实现')
  // 通常需要后端支持，这里只是示例
  // const url = `/api/system/quote/export?${objectToQueryString(queryParams)}`
  // window.open(url)
}

// 表单提交成功回调
const handleSuccess = () => {
  formVisible.value = false
  getList()
}
</script>

<style scoped>
.search-form {
  margin-bottom: 20px;
}

.table-operations {
  margin-bottom: 16px;
}

.danger-text {
  color: #ff4d4f;
}

.danger-text:hover {
  color: #ff7875;
}

.disabled-action {
  color: #d9d9d9;
  cursor: not-allowed;
}
</style>